'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 充值
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var moment = require('moment');
var async = require('async');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var payRecordModel = require('../../../models/payRecordModel');
var PlayerManager = require('../../../libs/playerManager');
var roleService = require('../../../services/roleService');
var payConf = require('../../../config/payConf');
var marqueeConf = require('../../../config/marqueeConf.js');
var analyze = require('../../../libs/analyze');
var vipConf = require('../../../config/vipConf.js');
var payProductType = require('../../../consts/payProductType');
var mailService = require('../../../services/mailService.js');
var genRewardService = require('../../../services/genRewardService');
var langUtil = require('../../../util/langUtil');
var configUtil = require('../../../util/configUtil');
var constantUtil = require('../../../util/constantUtil');
var redPacketModel = require('../../../models/redPacketModel');
var eventType = require('../../../consts/eventType');
var channelUtil = require('../../../util/channelUtil');
var mgrUtil = require('../../../util/mgrUtil');
var chatMgr = require('../../../mgr/chatMgr.js');
var marqueeModel = require('../../../models/marqueeModel.js');
var chatType = require('../../../consts/chatType.js');
var sysMsgType = require('../../../consts/sysMsgType.js');
var marqueeType = require('../../../consts/marqueeType.js');
var sysMsgConf = require('../../../config/sysMsgConf.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

Handler.prototype.checkOrder = function (msg, session, next) {
    var order_id = msg.query.order_id;
    var role_id = msg.query.role_id;
    var channel_id = msg.query.channel_id;
    var product_id = msg.query.product_id;
    var amount = msg.query.amount;
    var game_order = msg.query.game_order;
    if (!order_id || !role_id || !product_id || !amount) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }
    if (product_id > 10000) {
        product_id = Math.floor(product_id / 10000);
    }

    var role_model;
    // jshint maxstatements:150
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                payRecordModel.getOrder(order_id, cb);
            },
            function (model, cb) {
                if (!!model) {
                    return next(null, {
                        code: Code.OK
                    });
                }

                // 添加充值记录
                payRecordModel.addOrder(order_id, role_id, product_id, amount, cb);
            },
            function (model, cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'pay', 'task', 'copy', 'achieve', 'daily_task', 'wishtree', 'market', 'mail', 'accrued'], cb);
            },
            function (cb) {
                var pay_model = player_manager.pay;
                role_model = player_manager.role;
                var role_name = role_model.name;
                var name = '系统';
                if (!role_model) {
                    return next(null, {
                        code: Code.PAY_INVALID_ROLE_ID
                    });
                }

                // 首次充值标志
                var is_first_pay = (role_model.pay_diamond === 0);
                var pay_conf = payConf.getConf(product_id);
                if (!pay_conf) {
                    if (product_id === 190) {
                        product_id = 111;
                        pay_conf = payConf.getConf(product_id);
                    }
                    if (product_id === 200) {
                        product_id = 112;
                        pay_conf = payConf.getConf(product_id);
                    }
                }
                if (!pay_conf) {
                    return next(null, {
                        code: Code.PAY_INVALID_PRODUCT_ID
                    });
                }

                switch (pay_conf.type) {
                case payProductType.NORMAL:
                    {
                        break;
                    }
                case payProductType.MONTH:
                    {
                        // 添加月卡的天数
                        var month_day = payConf.getProductMonthDay(product_id);
                        pay_model.addMonthDay(month_day);

                        // 发送走马灯信息
                        var card_conf = marqueeConf.getConf(marqueeType.CARD);
                        var card_list = marqueeConf.getMsgConf(marqueeType.CARD);

                        // 发放广播
                        var card = sysMsgConf.getMsgConf(sysMsgType.ONEPAY);
                        var card_content = card_list[0].format;
                        var card_content_msg = card_content.replace(/name/, role_name);
                        var card_param = {
                            sort_id: card_conf.priority,
                            text: card_content_msg,
                            is_time: card_conf.fixed_time,
                            times: card_conf.times,
                            interval_time: card_conf.time
                        };
                        marqueeModel.create(card_param, function (err, module) {});
                        break;
                    }
                case payProductType.PERSISTENT:
                    {
                        // 设置至尊卡奖励额度
                        pay_model.setPersistentVal(pay_conf.rebate_num);

                        // 发送走马灯信息
                        var super_card_conf = marqueeConf.getConf(marqueeType.SUPERCARD);
                        var super_card_list = marqueeConf.getMsgConf(marqueeType.SUPERCARD);

                        // 发放广播
                        var super_card = sysMsgConf.getMsgConf(sysMsgType.ONEPAY);
                        var super_card_content = super_card_list[0].format;
                        var super_card_content_msg = super_card_content.replace(/name/, role_name);
                        var super_card_param = {
                            sort_id: super_card_conf.priority,
                            text: super_card_content_msg,
                            is_time: super_card_conf.fixed_time,
                            times: super_card_conf.times,
                            interval_time: super_card_conf.time
                        };

                        marqueeModel.create(super_card_param, function (err, module) {});

                        break;
                    }
                }

                // 首次购买相应分档充值
                if (pay_conf.type !== payProductType.MONTH && pay_conf.type !== payProductType.PERSISTENT) {
                    var first_pay_product = !pay_model.inPayList(product_id);
                    if (first_pay_product) {
                        roleService.addDiamond(player_manager, moduleType.MDL_PAY, operationType.OPR_PAY, pay_conf.rebate_num, product_id);
                    }
                    pay_model.addProductId(product_id);
                }

                var add_diamond = payConf.getProductDiamond(product_id, false);
                var old_vip_lv = role_model.getVip();
                roleService.addPayDiamond(player_manager, add_diamond, product_id);
                role_model.addPayVal(pay_conf.price);

                // 如果vip等级发生变化马上生效
                var new_vip_lv = role_model.getVip();
                if (new_vip_lv > old_vip_lv) {
                    roleService.vipChanged(player_manager, old_vip_lv, new_vip_lv);
                }

                // 首次充值
                if (is_first_pay) {
                    // 发放首充礼包
                    _doFirstPayReward(player_manager.mail, product_id);

                    // 发放广播
                    var one_pay = sysMsgConf.getMsgConf(sysMsgType.ONEPAY);
                    var one_pay_content = one_pay[0].format;
                    var one_pay_content_msg = one_pay_content.replace(/name/, role_name);
                    var one_pay_param = {
                        type: chatType.SYSTEM,
                        name: name,
                        msg: one_pay_content_msg,
                        time: moment().unix()
                    };
                    _chatMsg(one_pay_param);
                }

                // 单笔充值奖励
                if (pay_conf.price >= pay_model.next_single_pay) {
                    var now_pay_money = pay_conf.price;
                    var start_time = configUtil.getOpenGameTime();
                    var end_time = start_time + constantUtil.value('open_service_time') * configUtil.second_per_day;
                    var now_time = moment().unix();
                    if (start_time <= now_time && now_time <= end_time) {
                        _doSinglePayReward(player_manager.mail, pay_model.next_single_pay);
                        pay_model.next_single_pay = payConf.getNextSinglePayConf(pay_model.next_single_pay).id;
                    }

                    // 发放广播
                    var count_pay_list = sysMsgConf.getMsgConf(sysMsgType.ONEPAYNUM);
                    var count_pay_conf = sysMsgConf.getConf(sysMsgType.ONEPAYNUM);
                    _.some(count_pay_list, function (count_pay_item) {
                        if (count_pay_item.value == now_pay_money) {
                            var count_pay_content = count_pay_item.format;
                            var count_pay_content_msg = count_pay_content.replace(/name/g, role_name);
                            var name = '系统';
                            var count_pay_param = {
                                type: chatType.SYSTEM,
                                name: name,
                                msg: count_pay_content_msg,
                                time: moment().unix()
                            };
                            _chatMsg(count_pay_param);
                            return true;
                        }
                    });

                }

                // 统计
                _analyzePay(role_id, channel_id, {
                    uid: role_model.getUid(),
                    name: role_model.name,
                    order_id: order_id,
                    money: pay_conf.price,
                    lv: role_model.getLv(),
                    game_order: game_order
                });

                // 全服红包
                if (!!pay_conf.red_packet) {
                    _doSendRedPacket(role_model, pay_conf, function () {
                        player_manager.save(cb);
                    });
                } else {
                    player_manager.save(cb);
                }

            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 统计充值
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
var _analyzePay = function (role_id, channel_id, order_info) {
    analyze.recordPay(role_id, channel_id, order_info);
};

/**
 * 发放单笔充值礼包
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
var _doSinglePayReward = function (mail_model, product_id) {
    // 发放单笔充值礼包
    var reward_conf = payConf.getSinglePayReward(product_id);
    var reward_list = genRewardService.generateRewardList(reward_conf);
    var gift_name = payConf.getSinglePayConf(product_id).name;

    var title = langUtil.getString('one_time_pay_mail_title');
    var content = langUtil.getString('one_time_pay_mail_content');
    title = title.replace(/{GIFT_NAME}/gi, gift_name);
    content = content.replace(/{GIFT_NAME}/gi, gift_name);

    mailService.sendMail(mail_model, title, content, reward_list, moduleType.MDL_PAY, operationType.OPR_PAY, product_id);
};

/**
 * 发放首充礼包
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
var _doFirstPayReward = function (mail_model, product_id) {
    // 发放首充礼包
    var first_pay_conf = payConf.getFirstPayConf(1);
    var reward_list = genRewardService.generateRewardList(first_pay_conf);

    var title = langUtil.getString('pay_first_mail_title');
    var content = langUtil.getString('pay_first_mail_content');
    mailService.sendMail(mail_model, title, content, reward_list, moduleType.MDL_PAY, operationType.OPR_FIRST_PAY, product_id);
};

/**
 * 发放全服红包
 * @param  {[type]} role_id [description]
 * @return {[type]}         [description]
 */
var _doSendRedPacket = function (role_model, pay_conf, cb) {
    // 添加全服红包记录
    redPacketModel.create(pay_conf.red_packet_num, pay_conf.reward_type, pay_conf.min_red_packet, pay_conf.max_red_packet, pay_conf.big_packet, function (err, model) {
        var red_packet_id = model.red_packet_id;
        var red_packet_info = {
            red_packet_id: red_packet_id,
            role_name: role_model.name
        };

        // 全服广播
        mgrUtil.sendGlobalMessage(
            eventType.ON_RED_PACKET,
            red_packet_info,
            channelUtil.getGlobalChannelName(),
            cb
        );
    });
};

var _chatMsg = function (param) {
    chatMgr.sendWorld(param, function (err, fails) {
        if (err) {
            console.error('send message to world error: %j, fail ids: %j', err, fails);
            return;
        }
    });
};

var _marqueeMsg = function (param) {
    chatMgr.sendMarquee(param, function (err, res) {
        if (err) {
            console.error('send message to world and web--payHandler error: %j, fail ids: %j', err, res);
            return;
        }
    });
};
